package com.hulytu.invasion;


import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import com.hulytu.invasion.core.BuildConfig;
import com.hulytu.invasion.plugin.ActivityEnhancePlugin;
import com.hulytu.invasion.plugin.EnhancePlugin;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public class Embrace implements Application.ActivityLifecycleCallbacks {

    public static final int VERSION = BuildConfig.VERSION;

    private static final Object lock = new Object();

    public static void init(Context context, Elm elm) {
        synchronized (lock) {
            Holder.EMBRACE.doInit(context, elm);
        }
    }

    public static Application app() {
        return Holder.EMBRACE.app;
    }

    /**
     * 查找插件
     *
     * @param plugin
     * @return
     */
    public static <T> EnhancePlugin<T> findPlugin(String plugin) {
        return Holder.EMBRACE.store.findPlugin(plugin);
    }

    /**
     * 根据 host 查找对应插件
     *
     * @param plugin
     * @param host
     * @param create 如果没有是否尝试创建一个
     * @param <T>
     * @return
     * @since 1.0.2
     */
    public static <T> EnhancePlugin<T> findPlugin(String plugin, @NotNull T host, boolean create) {
        return EnhanceStoreV2.instance().findPlugin(plugin, host, create);
    }

    /**
     * 释放插件，仅限 {@link #findPlugin(String, Object, boolean)} 使用此方式创建的
     *
     * @param plugin
     * @param host
     * @since 1.0.2
     */
    public static void releasePlugin(String plugin, @NotNull Object host) {
        EnhanceStoreV2.instance().releasePlugin(plugin, host);
    }


    /**
     * 获取一些全局配置
     *
     * @return
     */
    @NotNull
    public static Planet planet() {
        Elm elm = Holder.EMBRACE.elm;
        Planet planet = elm == null ? null : elm.planet();
        return planet == null ? Planet.DEFAULT : planet;
    }

    /**
     * 获取所有插件
     *
     * @return
     * @since 1.0.1
     */
    public static List<EnhancePlugin<?>> allPlugins() {
        return Holder.EMBRACE.store.plugins();
    }

    /**
     * 判断当前是不是在UI进程
     *
     * @return
     */
    public static boolean isUiProcess() {
        return isUiProcess(app());
    }

    /**
     * @param ctx
     * @return
     * @since 1.0.2
     */
    public static boolean isUiProcess(Context ctx) {
        int pid = android.os.Process.myPid();

        ActivityManager manager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
        if (processes == null || processes.isEmpty()) return false;

        for (ActivityManager.RunningAppProcessInfo process : processes) {
            if (process.pid == pid) {
                return ctx.getPackageName().equals(process.processName);
            }
        }

        return false;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        Holder.EMBRACE.store.onActivityLifecycleCallback(ActivityEnhancePlugin.CREATE, activity, savedInstanceState);
    }

    @Override
    public void onActivityStarted(Activity activity) {
        Holder.EMBRACE.store.onActivityLifecycleCallback(ActivityEnhancePlugin.START, activity);
    }

    @Override
    public void onActivityResumed(Activity activity) {
        Holder.EMBRACE.store.onActivityLifecycleCallback(ActivityEnhancePlugin.RESUME, activity);
    }

    @Override
    public void onActivityPaused(Activity activity) {
        Holder.EMBRACE.store.onActivityLifecycleCallback(ActivityEnhancePlugin.PAUSE, activity);
    }

    @Override
    public void onActivityStopped(Activity activity) {
        Holder.EMBRACE.store.onActivityLifecycleCallback(ActivityEnhancePlugin.STOP, activity);
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        Holder.EMBRACE.store.onActivityLifecycleCallback(ActivityEnhancePlugin.DESTROY, activity);
    }

    private static class Holder {
        static final Embrace EMBRACE = new Embrace();
    }

    private Application app;

    private Elm elm;

    private final EnhanceStore store = new EnhanceStore();

    private Embrace() {
    }

    private void doInit(Context context, Elm elm) {
        // 无需重复初始化
        if (this.elm == elm || elm == null) return;

        if (context instanceof Application) {
            app = (Application) context;
        } else {
            app = (Application) context.getApplicationContext();
        }

        app.unregisterActivityLifecycleCallbacks(this);
        app.registerActivityLifecycleCallbacks(this);

        final Elm e = this.elm;
        if (e == null) {
            this.elm = elm;
        } else {
            e.setNext(elm);
        }

        List<EnhancePlugin<?>> plugins = elm.plugins(app);
        if (plugins == null || plugins.isEmpty()) return;

        List<EnhancePlugin<?>> list = store.filterAndRegister(plugins);

        for (EnhancePlugin<?> plugin : list) {
            plugin.onAppInit(app);
        }
    }


}
